from utils import upload_file,delete_file
from repositories.swiper_repo import SwiperRepo
from config import Config


class SwiperService:
    category = 'swipers'

    @staticmethod
    def add(name, file):
        filename = upload_file(file, SwiperService.category)
        swiper = {
            'url': filename,
            'name': name
        }

        SwiperRepo.insert(swiper)
        return filename

    @staticmethod
    def get_swipers_for_api():
        items = SwiperRepo.find_all()

        return [
            'http://127.0.0.1:8000/uploads/' + SwiperService.category + '/' + item.url

            for item in items
        ]


    @staticmethod
    def list():
        data = SwiperRepo.find_all()
        return [
            {
                'id': item.id,
                'url': f"/{Config.UPLOAD_FOLDER}/{SwiperService.category}/{item.url}",
                'name': item.name
            }
            for item in data
        ]

    @staticmethod
    def delete_by_id(id):
        data = SwiperRepo.find_by_id(id)
        if data:
            filename = data.url
            delete_file(filename, SwiperService.category)
            SwiperRepo.delete_by_id(id)





